import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/model/order_item.dart';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:gzmall_app/model/picture.dart';
import 'package:image_picker/image_picker.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/toast_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:gzmall_app/model/refund_reason.dart';

class OrderAfterSalePage extends StatefulWidget {
  OrderItem item;

  OrderAfterSalePage(this.item);

  @override
  State<StatefulWidget> createState() => OrderAfterSalePageState(this.item);
}

class OrderAfterSalePageState extends State<OrderAfterSalePage> {
  OrderItem item;
  List<String> _pictureIds = [];
  int _refundReasonId;
  String _refundReason;
  String _refundType;
  String _refundTypeName;
  String _refundDes;
  List<RefundReason> _refundReasonList = [];

  TextEditingController _contentController = TextEditingController();

  OrderAfterSalePageState(this.item);

  @override
  void initState() {
    super.initState();
    _getRefundReasons();
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> _imageWidget = [];
    if (_imageList != null && _imageList.length > 0) {
      _imageWidget = _imageList
          .map((i) => InkWell(
                onDoubleTap: () {
                  if (!mounted) return;
                  setState(() {
                    _imageList.remove(i);
                    _pictureIds.remove(i.id);
                  });
                },
                child: Padding(
                  padding: const EdgeInsets.only(right: 10.0),
                  child: CachedNetworkImage(
                    width: 80.0,
                    height: 80.0,
                    imageUrl: i.image,
                    fit: BoxFit.fill,
                  ),
                ),
              ))
          .toList();
    }
    if (_imageWidget.length < 3) {
      _imageWidget.add(
        InkWell(
          onTap: () {
            _showSelectPhoto();
          },
          child: Container(
            color: Colors.white,
            width: 80.0,
            height: 80.0,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Image.asset(
                  "images/add_photo.png",
                  width: 40.0,
                  height: 40.0,
                ),
                Text("照片"),
              ],
            ),
          ),
        ),
      );
    }
    return Scaffold(
      appBar: _createAppBar(),
      body: Container(
        color: ColorCommon.grey5,
        child: ListView(
          children: <Widget>[
            Container(
              color: Colors.white,
              width: double.infinity,
              padding: const EdgeInsets.all(10.0),
              child: Text(
                "退款商品",
                style: TextStyle(color: ColorCommon.black1, fontSize: 16.0),
              ),
            ),
            Container(
                color: Colors.white,
                padding: const EdgeInsets.all(10.0),
                margin: const EdgeInsets.only(bottom: 4.0),
                child: Row(
                  children: <Widget>[
                    item.avatar != null
                        ? CachedNetworkImage(
                            width: 80.0,
                            height: 80.0,
                            imageUrl: item.avatar,
                            fit: BoxFit.fill,
                          )
                        : Container(
                            width: 80.0,
                            height: 80.0,
                            color: ColorCommon.grey2,
                          ),
                    Expanded(
                      child: Container(
                        margin: const EdgeInsets.only(left: 10.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Container(
                              height: 50.0,
                              child: Text(
                                item.name ?? "",
                                style: TextStyle(
                                    color: ColorCommon.black1, fontSize: 16.0),
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                )),
            _createItemView(
                "售后类型",
                _refundTypeName ?? "请选择",
                _refundTypeName != null
                    ? ColorCommon.black1
                    : ColorCommon.grey4,
                EdgeInsets.only(top: 10.0), () {
              _showRefundType(context);
            }),
            _createItemView(
                "退款原因",
                _refundReason ?? "请选择",
                _refundReason != null ? ColorCommon.black1 : ColorCommon.grey4,
                EdgeInsets.only(top: 1.0), () {
              _showRefundReason(context);
            }),
            Container(
              color: Colors.white,
              padding: const EdgeInsets.all(10.0),
              child: Column(
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Padding(
                        padding: const EdgeInsets.only(right: 10.0),
                        child: Text(
                          "商品件数: ",
                          style: new TextStyle(fontSize: 16.0),
                        ),
                      ),
                      Text(
                        "x1",
                        style: new TextStyle(fontSize: 16.0),
                      ),
                    ],
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 10.0),
                    child: Row(
                      children: <Widget>[
                        Padding(
                          padding: const EdgeInsets.only(right: 10.0),
                          child: Text(
                            "退款金额: ",
                            style: new TextStyle(fontSize: 16.0),
                          ),
                        ),
                        Text(
                          "¥ 111.0",
                          style: new TextStyle(
                              fontSize: 18.0, color: ColorCommon.primaryColor),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              margin: const EdgeInsets.only(top: 10.0),
            ),
            Container(
              color: Colors.white,
              margin: const EdgeInsets.only(top: 10.0, bottom: 10.0),
              padding: const EdgeInsets.all(10.0),
              child: Row(children: <Widget>[
                Text(
                  "退款说明:",
                  style: TextStyle(fontSize: 16.0),
                ),
                Expanded(
                  child: Container(
                    margin: const EdgeInsets.only(left: 15.0),
                    child: TextField(
                      controller: _contentController,
                      style: TextStyle(color: ColorCommon.black1),
                      decoration: InputDecoration.collapsed(
                        hintText: "选填",
                        hintStyle:
                            TextStyle(fontSize: 16.0, color: ColorCommon.grey1),
                      ),
                      onChanged: (str) {
                        _refundDes = str ?? '';
                      },
                    ),
                  ),
                ),
              ]),
            ),
            Container(
              color: Colors.white,
              padding: const EdgeInsets.all(10.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.only(bottom: 10.0),
                    child: Text(
                      "上传凭证",
                      style: TextStyle(fontSize: 16.0),
                    ),
                  ),
                  Row(
                    children: _imageWidget,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  _createAppBar() {
    return AppBar(
      elevation: 0.0,
      title: Text("申请售后"),
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
      actions: <Widget>[
        InkWell(
          onTap: () {
            if (item != null) {
              if (_refundType == null || _refundType.isEmpty) {
                ToastUtil.showMessageToast("请选择售后类型");
                return;
              }
              if (_refundReasonId == null || _refundReasonId <= 0) {
                ToastUtil.showMessageToast("请选择退款原因");
                return;
              }
              _afterSale(item.id, _refundReasonId, item.fee, _refundReason,
                  _pictureIds, _refundType);
            }
          },
          child: Container(
            child: Text("提交"),
            alignment: Alignment.center,
            padding: EdgeInsets.only(right: 15.0),
          ),
        ),
      ],
    );
  }

  _createItemView(String title, String content, Color contentColor,
      EdgeInsetsGeometry margin, Function onTap) {
    return InkWell(
        onTap: onTap,
        child: Container(
          color: Colors.white,
          padding: const EdgeInsets.all(10.0),
          margin: margin,
          child: Row(
            children: <Widget>[
              new Expanded(
                child: new Text(
                  title,
                  style: new TextStyle(fontSize: 16.0),
                ),
              ),
              new Padding(
                padding: const EdgeInsets.only(right: 4.0),
                child: new GestureDetector(
                  onTap: onTap,
                  child: new Text(
                    content,
                    style: new TextStyle(fontSize: 16.0, color: contentColor),
                  ),
                ),
              ),
              new Image.asset(
                "images/right_arrow.png",
                width: 10.0,
                height: 10.0,
              ),
            ],
          ),
        ));
  }

  _showRefundReason(BuildContext context) {
    List<Widget> ws = _refundReasonList
        .map(
          (r) => _getRefundItem(r.name, () {
            if (!mounted) return;
            setState(() {
              _refundReason = r.name;
              _refundReasonId = r.id;
              Navigator.of(context).pop();
            });
          }),
        )
        .toList();
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          padding: const EdgeInsets.all(15.0),
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.only(bottom: 15.0),
                child: Text(
                  "退款原因",
                  style: TextStyle(fontSize: 18.0, color: ColorCommon.black1),
                ),
              ),
              Expanded(
                child: ListView(
                  children: ws,
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  _showRefundType(BuildContext context) {
    List<Widget> ws = [
      _getRefundItem("仅退款", () {
        if (!mounted) return;
        setState(() {
          _refundType = "refund";
          _refundTypeName = "仅退款";
          Navigator.of(context).pop();
        });
      }),
      _getRefundItem("退货退款", () {
        if (!mounted) return;
        setState(() {
          _refundType = "returned";
          _refundTypeName = "退货退款";
          Navigator.of(context).pop();
        });
      }),
    ];
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          padding: const EdgeInsets.all(15.0),
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.only(bottom: 15.0),
                child: Text(
                  "售后类型",
                  style: TextStyle(fontSize: 18.0, color: ColorCommon.black1),
                ),
              ),
              Expanded(
                child: ListView(
                  children: ws,
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _getRefundItem(String content, Function onTap) {
    return InkWell(
        onTap: onTap,
        child: Container(
          margin: const EdgeInsets.all(10.0),
          child: Row(
            children: <Widget>[
              Expanded(
                child: Text(content),
              ),
              Image.asset(
                "images/right_arrow.png",
                width: 10.0,
                height: 10.0,
              ),
            ],
          ),
        ));
  }

  _showSelectPhoto() {
    showCupertinoModalPopup(
      context: context,
      builder: (_) {
        return CupertinoActionSheet(
          actions: <Widget>[
            CupertinoActionSheetAction(
              onPressed: () {
                _getImage(ImageSource.camera);
                Navigator.of(context).pop();
              },
              child: Text("拍照"),
            ),
            CupertinoActionSheetAction(
              onPressed: () {
                _getImage(ImageSource.gallery);
                Navigator.of(context).pop();
              },
              child: Text("相册"),
            ),
          ],
          cancelButton: CupertinoActionSheetAction(
            onPressed: () {
              Navigator.of(context).pop();
            },
            child: Text("取消"),
          ),
        );
      },
    );
  }

  _afterSale(
      int itemId,
      int refundReasonId,
      String refundFee,
      String refundRemark,
      List<String> refundPicturesIds,
      String afterSaleType) {
    FormData formData = new FormData.fromMap({
      "order_item[refund_reason_id]": refundReasonId.toString(),
      "order_item[refund_fee]": refundFee.toString(),
      "order_item[refund_pictures_ids]": refundPicturesIds,
      "order_item[after_sale_type]": afterSaleType,
      "order_item[refund_remark]": refundRemark,
    });
    NetUtil.post(
        context, Api.orderItems + "/" + itemId.toString() + "/after_sale",
        (data, message) {
      ToastUtil.showMessageToast(message);
      Navigator.of(context).pop(true);
    }, params: formData, isShowLoading: true);
  }

  Future _getImage(ImageSource source) async {
    var image = await ImagePicker.pickImage(source: source, maxWidth: 600.0);

    if (!mounted) return;
    setState(() {
      _refundPicture(image);
    });
  }

  List<Picture> _imageList = [];
  _refundPicture(File image) {
    FormData formData = new FormData.fromMap(
        {"refund_picture[image]": MultipartFile.fromFileSync(image.path)});
    NetUtil.post(context, Api.refundPictures, (data, message) {
      ToastUtil.showMessageToast(message);
      Picture i = Picture.fromJson(data);
      if (!mounted) return;
      setState(() {
        _imageList.add(i);
        _pictureIds.add(i.id.toString());
      });
    }, params: formData, isShowLoading: true);
  }

  _getRefundReasons() {
    NetUtil.get(
      context,
      Api.refundReasons,
      (data, message) {
        if (!mounted) return;
        setState(() {
          _refundReasonList = (data as List)
              ?.map((e) => e == null ? null : RefundReason.fromJson(e))
              ?.toList();
        });
      },
    );
  }
}
